define('pc/js/mod/write/Editor', [
    'utils/fetchEnhancer',
    'editorenhancer/myalbum/MyAlbum',
    'editorenhancer/insertarticle/InsertArticle',
    'editorenhancer/ScrollFix',
    'editorenhancer/EnterHandler'], function(fetch, MyAlbum, InsertArticle, ScrollFix, EnterHandler){

var XEditor = window.XEditor;
var richEditor = null;
var doc = document;

XEditor.registerWidgetController('myalbum', MyAlbum);
XEditor.registerWidgetController('insertarticle', InsertArticle);

function handleKeyUp() {
    var words = richEditor.getPlainText().length;
    doc.getElementById('wordcount').innerHTML = '已输入 '+ words +' 个字';
}

return {
    init: function(id, type, widgets) {
        widgets = widgets || ['bold', 'blockquote', '-', 'image', 'myalbum', 'insertarticle'];

        richEditor = new XEditor({
            autoFocus: true,
            widgets: widgets,
            minHeight: '400',
            contentClassName: 'x-richcontent',
            widgetsOptions: {
                image: {
                    fieldName: 'editorfile',
                    accept: 'image/jpg, image/jpeg, image/png',
                    fileSizeLimit: 1024 * 1024,
                    beforeUpload: (callback) => {
                        fetch('/api/upload/pre?type=' + type).then((res) => {
                            if(0 === res.status) {
                                callback({
                                    server: res.data.server,
                                    params: res.data.params
                                });
                            } else {
                                XUI.toast.error('发生错误 ' + res.status);
                            }
                        });
                    },
                    uploadSuccess: (serverData) => {
                        var res = JSON.parse(serverData);
                        var project_id = res.data.project_id;
                        var uri = res.data.uri;

                        fetch('/api/upload/save', {
                            method: 'POST',
                            body: 'project_id='+ project_id +'&uri=' + encodeURIComponent(uri)
                        }).then(() => {});

                        return {
                            uri: uri
                        };
                    }
                }
            },
            plugins: [{
                className: ScrollFix,
                options: {
                    top: 46
                }
            }, {
                className: EnterHandler
            }]
        });
        richEditor.on('keyup', handleKeyUp);
        richEditor.render(doc.getElementById(id));

        return richEditor;
    }
};
});

